package com.zsx.shopping.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsx.shopping.product.converter.CategoryConverter;
import com.zsx.shopping.product.entity.Category;
import com.zsx.shopping.product.service.CategoryService;
import com.zsx.shopping.product.mapper.CategoryMapper;
import com.zsx.shopping.product.vo.CategoryVO;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private CategoryConverter categoryConverter;

    @Cacheable(value = "catalog", key = "'product'")
    @Override
    public List<CategoryVO> getCatalog() {
        List<CategoryVO> categoryVOs = new LinkedList<>();
        List<Category> categories = categoryMapper.selectList(null);

        // 建立id与categoryVO的映射关系
        Map<Long, CategoryVO> categoryVOMap = categories.stream().collect(Collectors.toMap(Category::getId, category -> {
            CategoryVO categoryVO = categoryConverter.toCategoryVO(category);
            categoryVO.setChildren(new LinkedList<>());
            return categoryVO;
        }));

        // 在map内部建立父子关系,并把一级分类组建为链表
        for (Category category : categories) {
            Long parentId = category.getParentId();
            Long categoryId = category.getId();
            if (parentId != 0) {
                categoryVOMap.get(parentId).getChildren().add(categoryVOMap.get(categoryId));
            } else {
                categoryVOs.add(categoryVOMap.get(categoryId));
            }
        }

        return categoryVOs;
    }
}




